<template>
  <div class="w-[100%] h-[100%]">

    <div class="mt-[0px]">
      <ContentWrap :show-border="false">
        <SearchBox :queryForm="searchList" :showExpland="false"  :show-export="false" @query="handleSearchQuery"
                   @update:exportData="exportData"
        />
      </ContentWrap>
    </div>



    <div class="mt-[30px]">
      <QueryTable
        pk="id"
        :list="dataList"
        :total="total"
        :btns="tableBtnList"
        @execute="handleBtnClick"
        v-model="queryParams"
        :thead="th"
        :show-action="false"
        :show-expand="false"
        :show-section="false"
      >

  <template #total>
    <div class="total">
      <QueryTable
        pk="id"
        :list="[]"
        :total="total"
        :btns="tableBtnList"
        @execute="handleBtnClick"
        v-model="queryParams"
        :thead="generateTh"
        :show-action="false"
        :show-expand="false"
        :show-section="false"
      />
    </div>

  </template>

      </QueryTable>

    </div>

  </div>
</template>
<script setup lang="ts">
import Icon from "@/components/Icon/src/Icon.vue"
import QueryTable from "@/components/TableData/index.vue"
import ImagePreview from "@/components/ImagePreview/index.vue"
import type {TradeOrderQueryVO} from "@/api/mall/trade/order";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import type {PurchaseAdvice} from "@/api/purchase/advice/type";
import {
  exportByMember,
  getOrderStatisticsByDept,
  getOrderStatisticsByDeptTotal,
  getOrderStatisticsByMemberTotal,exportByDepartment
} from "@/api/statistics/order";
import {getSimpleDeptList} from "@/api/system/dept";
import {getUserPageNew} from "@/api/member/user";
import download from "@/utils/download";

const config = ref([
  {
    name: "总订单数",
    code: "totalCount",
    unit: "单位--",
    icon: "eq"
  },
  {
    name: "营业额",
    code: "totalAmount",
    unit: "单位￥",
    icon: "plus"
  },
  {
    name: "有效订单数",
    code: "validCount",
    unit: "单位/个",
    icon: "plus"
  },
  {
    name: "无效订单数",
    code: "invalidCount",
    unit: "单位/个",
    icon: "plus"
  },
  {
    name: "发货数",
    code: "shippedCount",
    unit: "单位/件",
    icon: "plus"
  },
  {
    name: "签收数",
    code: "signedCount",
    unit: "单位/件",
    icon: "plus"
  },
  {
    name: "拒收数",
    code: "rejectedCount",
    unit: "单位--",
    icon: ""
  }
])

const totalData = ref({})

const searchList = ref(
  [
    {
      label: '部门',
      code: 'deptId',
      type: 'select',
      options:[]
    },

    {
      label: '日期',
      code: 'createdTime',
      type: 'dateRange'
    }
  ]
)

const initQueryParams = {
  pageNo: 1, pageSize: 10
}


const tableBtnList = ref([
  {
    color: '#3721FF',
    code: 'detail',
    name: '详情'
  }
]);


const th = ref([

  {
    name: '部门',
    code: 'deptName',
    type: 'date',
    search: true,
    isnor:true
  },

  {
    name: '总订单数',
    code: 'totalCount',
    type: 'numberRanger',
    search: true
  },
  {
    name: '营业额',
    code: 'totalAmount',
    search: false
  },
  {
    name: '客单价',
    code: 'avgValue',
    search: false
  },
  {
    name: '有效订单数',
    code: 'validCount',
    search: false
  },
  {
    name: '无效订单数',
    code: 'invalidCount',
    search: false
  },
  {
    name: '发货数',
    code: 'shippedCount',
    search: false
  },
  {
    name: '有效比',
    code: 'validRatio',
    search: false,
    isnor:true
  },
  {
    name: '签收数',
    code: 'signedCount',
    search: false
  },
  {
    name: '签收率',
    code: 'signRate',
    search: false,
    isnor:true
  },
  {
    name: '拒收数',
    code: 'rejectedCount',
    search: false
  },
  {
    name: '拒收率',
    code: 'rejectionRate',
    search: false,
    isnor:true
  }
]);


const dataList = ref<PurchaseAdvice[]>([]);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const generateTh=computed(()=>{
  let th1 = [];
  th.value.forEach((item,index)=>{

    let option = {
      name: '',
      code: 'deptName',
    }
    if(index == 0){
      option.name = '合计'
    }else{
      if(item.isnor){
        option.name = ' '
      }else{
        option.name =totalData.value[item.code] || '0'
      }

    }
    th1.push(option)
  })
  return th1
})

const initRow = {
  cover: null,
  sku: null,
  spec: null,
  name: null,
  productId: null,
  advice: null,
  occupy: null,
  stock: null,
  inTransit: null,
  noAuditInTransit: null,
}

const selectedRow = ref<PurchaseAdvice>({...initRow})

const isShowDialog = ref(false)


const queryParams = ref({
  ...initQueryParams
})

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  queryParams.value={
    ...initQueryParams,
    ...val
  }
  getList();
}

const handleBtnClick = e => {
  let type = e.type;
  try {
    fn[type](e)
  } catch (e) {
    console.log(`${type}不存在`)
  }
}

const fn = {
  detail({data}) {
    selectedRow.value = data.row;
    isShowDialog.value = true
  }
}

const getList = async () => {
  let option = {
    ...queryParams.value,
    beginTime:queryParams.value.createdTime && queryParams.value.createdTime.length>0 ? queryParams.value.createdTime[0]:null ,
    endTime:queryParams.value.createdTime && queryParams.value.createdTime.length>0 ? queryParams.value.createdTime[1]:null ,
  }
  let res = await getOrderStatisticsByDept(option);
  dataList.value = res.list;
  total.value = res.total;


  res = await getOrderStatisticsByMemberTotal(option);
  totalData.value = res || {}
  console.log(res)
}

const onChange = ({item, form}) => {
  console.log("11111")
  console.log(item)
  if (item.code == "deptId") {
    getUser(form.deptId);
  }
}


/**
 * 根据部门获取
 * */
const getUser = async (deptId) => {
  let res = await getUserPageNew({
    deptId
  });

  let item = searchList.value.find(at => {
    return at.code == "userId"
  })
  item.options = (res || []).map(item => {
    return {
      label: item.nickname,
      value: item.id
    }
  });
}

const exportData=async e=>{
  console.log("???")
  let res = await exportByDepartment(queryParams.value);
  console.log(res,"rr")
  download.excel(res, '订单分析按部门.xls')

}



const initPromise = async () => {
  let res = await Promise.all([getSimpleDeptList()])
  //获取部门
  let item = searchList.value.find(it => {
    return it.code == "deptId"
  })
  console.log(item, "====iiii")
  item.options = res[0]?.map(item => {
    return {
      label: item.name,
      value: item.id
    }
  })


}



onMounted(() => {
  getList();

  initPromise();


})

</script>
<style lang="scss" scoped>
.total{
  :deep(.el-table__empty-block){display:none;}

  :deep(.el-table__inner-wrapper):before{
    display:none;
  }
}
</style>
